package cn.bdqn.realm;

import cn.bdqn.sys.entity.Permission;
import cn.bdqn.sys.entity.Role;
import cn.bdqn.sys.entity.User;
import cn.bdqn.sys.service.IPermissionService;
import cn.bdqn.sys.service.IRoleService;
import cn.bdqn.sys.service.IUserService;
import cn.bdqn.utils.ShiroUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private IPermissionService iPermissionService;
    @Override
    //控制角色权限
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 这里做权限控制
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        String username = (String) principals.getPrimaryPrincipal();
        //将当前用户的角色和权限复制进来
        User user = iUserService.selectUserByUsername(username);

        Role role =iRoleService.getOne(new QueryWrapper<Role>().eq("userid",user.getId()));
        info.addRole(role.getRolename());

        List<Permission> permissions= iPermissionService.list(new QueryWrapper<Permission>().eq("roleid",role.getId()));
        List<String> perlist  =new ArrayList<>();
        permissions.forEach(permission -> {
            perlist.add((permission.getPermission()));
        });

        info.addStringPermissions(perlist);
        return info;
    }
    //控制登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 这里做登录控制

        AuthenticationInfo info;
        String username = (String) token.getPrincipal();
        User user=iUserService.selectUserByUsername(username);
        if(user!=null){
            info =  new SimpleAuthenticationInfo(username,"",getName());
            System.out.println(getName());
            return info;
        }
        return null;
    }
/*	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
		shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
		shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
		super.setCredentialsMatcher(shaCredentialsMatcher);
	}  */  
}

